<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="car-form-container">
    <h1>汽车信息提交</h1>

    <form @submit.prevent="handleSubmit" class="car-form">
      <!-- 汽车名称 -->
      <div class="form-group">
        <label for="name">汽车名称：</label>
        <input
          id="name"
          v-model="carForm.name"
          type="text"
          required
          :disabled="submitting"
          placeholder="请输入汽车名称"
        />
      </div>

      <!-- 汽车品牌 -->
      <div class="form-group">
        <label for="brand">汽车品牌：</label>
        <input
          id="brand"
          v-model="carForm.brand"
          type="text"
          required
          :disabled="submitting"
          placeholder="请输入汽车品牌"
        />
      </div>

      <!-- 汽车价格 -->
      <div class="form-group">
        <label for="price">汽车价格：</label>
        <input
          id="price"
          v-model.number="carForm.price"
          type="number"
          min="0"
          step="0.01"
          required
          :disabled="submitting"
          placeholder="请输入汽车价格"
        />
      </div>

      <!-- 汽车图片上传 -->
      <div class="form-group">
        <label>汽车图片：</label>
        <div class="upload-section">
          <input
            ref="fileInput"
            type="file"
            accept="image/*"
            @change="handleFileSelect"
            :disabled="submitting || uploading"
          />
          <button type="button" @click="triggerFileSelect" :disabled="submitting || uploading">
            选择图片
          </button>
        </div>

        <!-- 图片预览 -->
        <div v-if="previewUrl" class="preview-section">
          <img :src="previewUrl" alt="汽车图片预览" class="preview-image" />
          <p>{{ selectedFile?.name }}</p>
          <p class="info-text">图片将在提交表单时自动上传</p>
        </div>

        <!-- 上传进度 -->
        <div v-if="uploading" class="progress-section">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: uploadProgress.percent + '%' }"></div>
          </div>
          <p>正在上传图片: {{ uploadProgress.percent }}%</p>
        </div>
      </div>

      <!-- 提交按钮 -->
      <div class="form-actions">
        <button
          type="submit"
          :disabled="submitting || uploading || !isFormValid"
          class="submit-btn"
        >
          {{ submitting ? (uploading ? '正在上传图片...' : '正在提交...') : '提交汽车信息' }}
        </button>
        <button
          type="button"
          @click="resetForm"
          :disabled="submitting || uploading"
          class="reset-btn"
        >
          重置表单
        </button>
      </div>
    </form>

    <!-- 提交结果 -->
    <div v-if="submitResult" class="result-section">
      <h3>提交成功！</h3>
      <pre>{{ JSON.stringify(submitResult, null, 2) }}</pre>
    </div>

    <!-- 错误信息 -->
    <div v-if="errorMessage" class="error-section">
      <h3>操作失败</h3>
      <p>{{ errorMessage }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { getCarInfo } from '@/api/mainController'
import { cosUpload, type UploadProgress } from '@/cos/cosUpload'

// 表单数据
const carForm = ref<API.Car>({
  name: '',
  brand: '',
  price: undefined,
  photo: '',
})

// 文件上传相关
const fileInput = ref<HTMLInputElement>()
const selectedFile = ref<File | null>(null)
const previewUrl = ref<string>('')
const uploading = ref(false)
const uploadProgress = ref<UploadProgress>({
  loaded: 0,
  total: 0,
  speed: 0,
  percent: 0,
})

// 提交状态
const submitting = ref(false)
const submitResult = ref<API.Car | null>(null)
const errorMessage = ref<string>('')

// 表单验证
const isFormValid = computed(() => {
  return (
    carForm.value.name &&
    carForm.value.brand &&
    carForm.value.price !== undefined &&
    carForm.value.price > 0 &&
    selectedFile.value // 只需要选择了文件即可，不需要已上传
  )
})

// 触发文件选择
const triggerFileSelect = () => {
  fileInput.value?.click()
}

// 处理文件选择
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]

  if (file) {
    selectedFile.value = file

    // 创建预览URL
    if (previewUrl.value) {
      URL.revokeObjectURL(previewUrl.value)
    }
    previewUrl.value = URL.createObjectURL(file)

    // 清除错误信息
    errorMessage.value = ''
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!isFormValid.value) {
    errorMessage.value = '请填写完整的表单信息并选择图片'
    return
  }

  try {
    submitting.value = true
    uploading.value = true
    errorMessage.value = ''
    submitResult.value = null

    // 先上传图片
    if (selectedFile.value) {
      const uploadResult = await cosUpload(selectedFile.value, (progress: UploadProgress) => {
        uploadProgress.value = progress
      })

      // 将上传成功的URL保存到表单中
      carForm.value.photo = uploadResult.url
    }

    uploading.value = false

    // 然后提交表单数据
    const response = await getCarInfo(carForm.value)
    submitResult.value = response.data.data ?? null
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : '提交失败'
  } finally {
    submitting.value = false
    uploading.value = false
  }
}

// 重置表单
const resetForm = () => {
  // 重置表单数据
  carForm.value = {
    name: '',
    brand: '',
    price: undefined,
    photo: '',
  }

  // 清除文件选择
  selectedFile.value = null
  if (fileInput.value) {
    fileInput.value.value = ''
  }

  // 清除预览URL
  if (previewUrl.value) {
    URL.revokeObjectURL(previewUrl.value)
    previewUrl.value = ''
  }

  // 重置状态
  uploading.value = false
  submitting.value = false
  uploadProgress.value = {
    loaded: 0,
    total: 0,
    speed: 0,
    percent: 0,
  }
  submitResult.value = null
  errorMessage.value = ''
}
</script>

<style scoped>
.car-form-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.car-form {
  background: #f9f9f9;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #333;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.form-group input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.upload-section {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 15px;
}

.upload-section input[type='file'] {
  display: none;
}

.upload-section button {
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.upload-section button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.preview-section {
  margin-top: 15px;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
}

.preview-image {
  max-width: 200px;
  max-height: 200px;
  object-fit: contain;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 10px;
}

.info-text {
  color: #6c757d;
  font-style: italic;
  margin: 5px 0;
}

.progress-section {
  margin-top: 15px;
}

.progress-bar {
  width: 100%;
  height: 20px;
  background-color: #f0f0f0;
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 8px;
}

.progress-fill {
  height: 100%;
  background-color: #007bff;
  transition: width 0.3s ease;
}

.uploaded-section {
  margin-top: 15px;
  padding: 10px;
  background-color: #d4edda;
  border: 1px solid #c3e6cb;
  border-radius: 4px;
}

.success-text {
  color: #155724;
  margin: 0 0 5px 0;
  font-weight: bold;
}

.photo-link {
  color: #007bff;
  text-decoration: none;
}

.photo-link:hover {
  text-decoration: underline;
}

.form-actions {
  display: flex;
  gap: 15px;
  margin-top: 30px;
}

.submit-btn {
  flex: 1;
  padding: 12px 24px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
}

.reset-btn {
  padding: 12px 24px;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.submit-btn:disabled,
.reset-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.submit-btn:hover:not(:disabled) {
  background-color: #218838;
}

.reset-btn:hover:not(:disabled) {
  background-color: #5a6268;
}

.result-section {
  margin-top: 30px;
  padding: 20px;
  background-color: #d4edda;
  border: 1px solid #c3e6cb;
  border-radius: 4px;
}

.result-section h3 {
  color: #155724;
  margin-top: 0;
}

.result-section pre {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
  white-space: pre-wrap;
}

.error-section {
  margin-top: 30px;
  padding: 20px;
  background-color: #f8d7da;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
  color: #721c24;
}

.error-section h3 {
  margin-top: 0;
}

h1 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}

@media (min-width: 1024px) {
  .car-form-container {
    padding: 40px 20px;
  }
}
</style>
